﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Framework.Utility;
using System.ComponentModel;
using Sector7.Medical.Biz;
using Sector7.Framework.Consts;
using Sector7.Medical.Consts;
using Sector7.Medical.Controls;
using Sector7.Medical.EntityType;
using Sector7.Framework.Enums;
using System.Reflection;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// RegistryChargeSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class RegistryFeeSummaryControl : SummaryControlBase
    {
        #region Accessor
        public M7_RegistryFee RegistryFee
        {
            get { return m_entity as M7_RegistryFee; }
            set { m_entity = value; }
        }
        #endregion

        #region Public Functions
        #endregion

        #region Private Function
        private void LoadData()
        {
            ClientUtil.LoadItemsSource(cbbDeptList, m_deptList);
            ClientUtil.LoadItemsSource(cbbOutpaientType, m_outpatientTypeList);
            ClientUtil.LoadItemsSource(cbbRegistryType, m_registryTypeList);
            ClientUtil.LoadItemsSource(dtgMain, m_feeList);

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Senvironments.ProgressWindow.Visibility = Visibility.Visible;
            SwitchProperityGroupEnableState(false);

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerAsync();
        }

        private void GetData()
        {
            m_feeList = Agent_INFS.GetRegistryFeeList();
            m_tempFeeList.AddRange(m_feeList.ToArray());
            m_deptList = Agent_INFS.GetDepartmentListByComflags(
                C_DepartmentFlags.DEPARTMENT |
                C_DepartmentFlags.CAN_REGISTRY | 
                C_DepartmentFlags.CAN_CHARGE);

            m_outpatientTypeList = new List<M7_OutpatientType>();
            FieldInfo[] oFieldArr = typeof(C_OutpatientType).GetFields();
            foreach (FieldInfo field in oFieldArr)
            {
                object[] attributeArrary = field.GetCustomAttributes(typeof(ConstAttribute), true);
                if (attributeArrary.Length == 1)
                {
                    ConstAttribute attribute = attributeArrary[0] as ConstAttribute;
                    string displayText = attribute.DisplayText;
                    if (!string.IsNullOrEmpty(displayText))
                    {
                        object value = field.GetValue(null);
                        if (value is int)
                        {
                            m_outpatientTypeList.Add(new M7_OutpatientType(Convert.ToInt32(value), displayText));
                        }
                    }
                }
            }

            m_registryTypeList = new List<M7_RegistryType>();
            FieldInfo[] rFieldArr = typeof(C_RegistryType).GetFields();
            foreach (FieldInfo field in rFieldArr)
            {
                object[] attributeArrary = field.GetCustomAttributes(typeof(ConstAttribute), true);
                if (attributeArrary.Length == 1)
                {
                    ConstAttribute attribute = attributeArrary[0] as ConstAttribute;
                    string displayText = attribute.DisplayText;
                    if (!string.IsNullOrEmpty(displayText))
                    {
                        object value = field.GetValue(null);
                        if (value is int)
                        {
                            m_registryTypeList.Add(new M7_RegistryType(Convert.ToInt32(value), displayText));
                        }
                    }
                }
            }

            foreach (M7_RegistryFee rf in m_feeList)
            {
                SetRegistryFeeInfor(rf);
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        private void dtgMain_SelectionChanged(object obj, RoutedEventArgs e)
        {
            var selectedItem = dtgMain.SelectedItem as M7_RegistryFee;
            if (selectedItem != null)
            {
                SetDetailControls(selectedItem);
                SwitchEditableButtonsStatus(CrudType.Read);
                SwitchProperityGroupEnableState(false);
            }
            else
            {
                ResetDetailControls();
                SwitchEditableButtonsStatus(CrudType.Create);
            }
        }

        /// <summary>
        /// Set RegistryFee Infor
        /// </summary>
        /// <param name="registryFee"></param>
        private void SetRegistryFeeInfor(M7_RegistryFee registryFee)
        {
            registryFee.OutpatientTypeObject = m_outpatientTypeList.Find(delegate(M7_OutpatientType __outpatientType)
            {
                return __outpatientType.OutpatientTypeId == registryFee.OutpatientType;
            });
            registryFee.RegistryTypeObject = m_registryTypeList.Find(delegate(M7_RegistryType __registryType)
            {
                return __registryType.RegistryTypeId == registryFee.RegistryType;
            });
            registryFee.Dept = m_deptList.Find(delegate(M7_Department __dept)
            {
                return __dept.DeptId == registryFee.DeptId;
            });
        }

        private void SwitchProperityGroupEnableState(bool isEnable)
        {
            cbbDeptList.IsEnabled = isEnable;
            cbbOutpaientType.IsEnabled = isEnable;
            cbbRegistryType.IsEnabled = isEnable;
            txbOutpaient.IsEnabled = isEnable;
            txbRegistryFee.IsEnabled = isEnable;
            txbRemarks.IsEnabled = isEnable;
            ckbIsValid.IsEnabled = isEnable;
        }

        protected override void SetDetailControls(object entity)
        {
            M7_RegistryFee fee = entity as M7_RegistryFee;
            if (fee != null)
            {
                cbbDeptList.SelectedValue = fee.DeptId;
                txbOutpaient.Text = fee.DiagnosticFee.ToString();
                txbRegistryFee.Text = fee.RegistryFee.ToString();
                txbRemarks.Text = fee.Remarks.ToString();
                cbbOutpaientType.SelectedValue = fee.OutpatientType;
                cbbRegistryType.SelectedValue = fee.RegistryType;
                ckbIsValid.IsChecked = (bool)fee.IsValid;
            }
            base.SetDetailControls(entity);
        }

        protected override void ResetDetailControls()
        {
            cbbDeptList.SelectedIndex = 0;
            cbbOutpaientType.SelectedIndex = 0;
            cbbRegistryType.SelectedIndex = 0;
            txbOutpaient.Text = string.Empty;
            txbRegistryFee.Text = string.Empty;
            txbRemarks.Text = string.Empty;;
            ckbIsValid.IsChecked = false;
        }

        protected override bool CheckData()
        {
            m_errors.Clear();

            string outpaient = txbOutpaient.Text.Trim();
            string registryFee = txbRegistryFee.Text.Trim();
            string remarks = txbRemarks.Text.Trim();

            //bool outpaientValid = RegularUtil.IsDecimal(outpaient);
            //bool registryFeeValid = RegularUtil.IsDecimal(registryFee);
            int remarkLen = remarks.ToString().Length;

            try
            {
                Convert.ToDecimal(registryFee);
            }
            catch
            {
                m_errors.Add("挂号费错误", "请输入数字或小数!");
            }

            try
            {
                Convert.ToDecimal(outpaient);
            }
            catch
            {
                m_errors.Add("诊查费错误", "请输入数字或小数!");
            }

            //if (!outpaientValid)
            //{
            //    m_errors.Add("诊查费错误", "请输入数字或小数!");
            //}
            //if (!registryFeeValid)
            //{
            //    m_errors.Add("挂号费错误", "请输入数字或小数!");
            //}

            if (remarkLen > C_MaxSize.REMARKS_MAX_SIZE)
            {
                m_errors.Add("备注长度错误", "最大长度为124!");
            }

            return base.CheckData();
        }

        protected override void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            SwitchProperityGroupEnableState(true);
            InitializeControl(CrudType.Create);
            base.btnAdd_Click(sender, e);
        }

        protected override void btnModify_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_RegistryFee)
            {
                var fee = dtgMain.SelectedItem as M7_RegistryFee;
                RegistryFee = fee;
                InitializeControl(CrudType.Update);
                SwitchProperityGroupEnableState(true);
            }
            base.btnModify_Click(sender, e);
        }


        protected override void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckData())
            {
                ShowErrors();
            }
            else
            {
                if (m_crud == CrudType.Update)
                {
                    var selectedItem = dtgMain.SelectedItem as M7_RegistryFee;
                    RegistryFee.FeeId = selectedItem.FeeId;
                }
                else
                {
                    RegistryFee = new M7_RegistryFee();
                }
                
                RegistryFee.DeptId = (cbbDeptList.SelectedItem as M7_Department).DeptId;
                RegistryFee.OutpatientType = Convert.ToInt32(cbbOutpaientType.SelectedValue);
                RegistryFee.RegistryType = Convert.ToInt32(cbbRegistryType.SelectedValue);
                RegistryFee.DiagnosticFee = Convert.ToDecimal(txbOutpaient.Text);
                RegistryFee.RegistryFee = Convert.ToDecimal(txbRegistryFee.Text);
                RegistryFee.Remarks = txbRemarks.Text;
                RegistryFee.IsValid = (bool)ckbIsValid.IsChecked;

                switch (m_crud)
                {
                    case CrudType.Create:
                        object feeId = Agent_INFS.AddRegistryFee(RegistryFee);
                        if (feeId != null)
                        {
                            RegistryFee.FeeId = Convert.ToInt32(feeId);
                            SetRegistryFeeInfor(RegistryFee);
                            m_feeList.Add(RegistryFee);
                            m_tempFeeList.Add(RegistryFee);
                            dtgMain.Items.Refresh();
                        }
                        break;
                    case CrudType.Update:
                        bool isChanged = false;
                        var delta = GetDelta("FeeId", ref isChanged);
                        if (isChanged)
                        {
                            Agent_INFS.UpdateRegistryFee(delta);
                            dtgMain.Items.Refresh();
                        }
                        break;
                    default:
                        break;
                }
                base.btnOk_Click(sender, e);
            }
        }

        protected override void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var selectItem = dtgMain.SelectedItem as M7_RegistryFee;
            if (selectItem != null)
            {
                MessageBoxResult mbr = Alert.ShowDialog(AlertType.Question, "是否确定删除该挂号费?");
                if (mbr == MessageBoxResult.Yes)
                {
                    int ret = Agent_INFS.DeleteRegistryFee(selectItem.FeeId);
                    if (ret > 0)
                    {
                        if (m_feeList.Contains(selectItem))
                        {
                            m_feeList.Remove(selectItem);
                            dtgMain.Items.Refresh();
                        }


                        if (m_tempFeeList.Contains(selectItem))
                        {
                            m_tempFeeList.Remove(selectItem);
                        }
                    }
                }
            }
            base.btnDelete_Click(sender, e);
        }

        protected override void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = dtgMain.SelectedItem as M7_RegistryFee;

            if (selectedItem != null)
            {
                SetDetailControls(selectedItem);
            }

            base.btnCancel_Click(sender, e);
        }

        /// <summary>
        /// 选中Item颜色改变
        /// </summary>
        /// <param name="area"></param>
        private void SelectRoomItem(M7_RegistryFee fee)
        {
            if (dtgMain.Items.Contains(fee))
            {
                dtgMain.SelectedItem = fee;
            }
        }

        protected override void InitializeForCreating()
        {
            ResetDetailControls();
            base.InitializeForCreating();
        }

        protected override void InitializeForUpdating()
        {
            SetDetailControls(RegistryFee);
            base.InitializeForUpdating();
        }

        private void searchBox_KeywordsChanging(object obj, EventArgs e)
        {
            string keywords = searchBox.Keywords;

            m_feeList = m_tempFeeList.FindAll(delegate(M7_RegistryFee __registryFee)
            {
                if (__registryFee.FeeId.ToString().Contains(keywords))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            ClientUtil.LoadItemsSource(dtgMain, m_feeList);
        }

        private void searchBox_KeywordsReset(object obj, EventArgs e)
        {
            m_feeList.Clear();
            m_feeList.AddRange(m_tempFeeList.ToArray());

            ClientUtil.LoadItemsSource(dtgMain, m_feeList);
        }
        #endregion

        #region Structrue
        public RegistryFeeSummaryControl()
        {
            InitializeComponent();

            m_btnAdd = btnAdd;
            m_btnModify = btnModify;
            m_btnDelete = btnDelete;
            m_btnOk = btnOk;
            m_btnCancel = btnCancel;
        }
        #endregion

        #region Inner Members
        /// <summary>
        /// 获取所有挂号费信息列表
        /// </summary>
        private List<M7_RegistryFee> m_feeList = null;

        /// <summary>
        /// 获取所有挂号费信息列表
        /// </summary>
        private List<M7_RegistryFee> m_tempFeeList = new List<M7_RegistryFee>();

        /// <summary>
        /// 获取所有一级科室列表
        /// </summary>
        private List<M7_Department> m_deptList = null;

        /// <summary>
        /// 获取所有挂号费类型列表
        /// </summary>
        private List<M7_RegistryType> m_registryTypeList = null;

        /// <summary>
        /// 获取所有门诊类型列表
        /// </summary>
        private List<M7_OutpatientType> m_outpatientTypeList = null;
        #endregion
    }
}